<?php

namespace app\admin\controller\tree\config;

use app\admin\service\ConfigService;
use app\BaseController;
use app\common\service\TreeSensitiveFilterService;
use app\model\tree\TreeFruitImgModel;
use app\model\tree\TreeFruitLikeModel;
use app\model\tree\TreeFruitModel;
use app\model\tree\TreeUserInfoModel;
use app\model\UnitModel;
use PhpOffice\PhpSpreadsheet\IOFactory;
use think\App;

class Fruit extends BaseController
{

    public function __construct(App $app)
    {
        parent::__construct($app);
    }

    /**
     * 智慧果管理列表
     * @return bool|string
     */
    public function index(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param, [
//                'type|类型' => 'require|in:1,2',
                'pageSize|每页显示数' => 'require',
            ]);
            $where = [];
            if (!empty($param['content'])) {
                $where[] = ['content', 'like', '%' . $param['content'] . '%'];
            }
            if (!empty($param['start_time']) && !empty($param['end_time'])) {
                $where[] = ['time', 'between', [$param['start_time'], $param['end_time']]];
            } else {
                if (!empty($param['start_time'])) {
                    $where[] = ['time', '>=', $param['start_time']];
                }
                if (!empty($param['end_time'])) {
                    $where[] = ['time', '<=', $param['end_time']];
                }
            }
            if (isset($param['is_file']) && strlen($param['is_file']) > 0) {
                $where[] = ['is_file', '=', $param['is_file']];
            }
            if (isset($param['status']) && strlen($param['status']) > 0) {
                $where[] = ['status', '=', $param['status']];
            }
            if (isset($param['is_nickname']) && strlen($param['is_nickname']) > 0) {
                $where[] = ['is_nickname', '=', $param['is_nickname']];
            }
            $where[] = ['type', '=', $param['type']];
            $where[] = ['unit_id', '=', $this->userData['unit_id']];
            $TreeFruitModel = new TreeFruitModel();
            $query = $TreeFruitModel->where($where);
            $data = $query->with(['user', 'treeUserInfo', 'fruitImg'])->paginate($param['pageSize'])->toArray();
            foreach ($data['data'] as &$v) {
                if (!empty($v['file']) && !empty($v['fruitImg'])) {
                    $v['icon_status'] = 1;
                } elseif (!empty($v['file'])) {
                    $v['icon_status'] = 2;
                } elseif (!empty($v['fruitImg'])) {
                    $v['icon_status'] = 3;
                } else {
                    $v['icon_status'] = 0;
                }
                if ($v['is_nickname']) {
                    $v['user_name'] = $v['nickname'];
                    $v['avatar'] = $v['nickname_avatar'];
                }
                unset($v['nickname']);
                unset($v['nickname_avatar']);
            }
            $data['ids'] = $query->column('id');
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 智慧果详情
     * @return bool|string
     */
    public function info(): bool|string
    {
        try {
            $id = $this->request->param('id');
            $TreeFruitModel = new TreeFruitModel();
            $info = $TreeFruitModel->with([
                'user',
                'treeUserInfo',
                'fruitComment' => function ($query) {
                    $query->with(['user', 'treeUserInfo']);
                },
                'fruitImg'
            ])->find($id);
            if ($info) {
                $info = $info->toArray();
                $info['comment_num'] = count($info['fruitComment']);
                if ($info['is_nickname']) {
                    $info['user_name'] = $info['nickname'];
                    $info['avatar'] = $info['nickname_avatar'];
                }
                unset($info['nickname']);
                unset($info['nickname_avatar']);
                $TreeFruitLikeModel = new TreeFruitLikeModel();
                $is_like = $TreeFruitLikeModel->where([
                    ['fruit_id', '=', $id],
                    ['uid', '=', $this->userData['id']]
                ])->value('id');
                $info['is_like'] = $is_like ? 1 : 0;
            }
            return success($info);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 智慧果添加
     * @return bool|string
     */
    public function add(): bool|string
    {
        $TreeFruitModel = new TreeFruitModel();
        $TreeFruitModel->startTrans();
        try {
            $param = $this->request->param();
            $this->validate($param, [
                'content|内容' => 'require',
            ]);
            $param['unit_id'] = $this->userData['unit_id'];
            $param['uid'] = $this->userData['id'];
            $param['time'] = time();
            if (!empty($param['img']) || !empty($param['file'])) {
                $param['is_file'] = 1;
            }
            if (!empty($param['img'])) {
                $imgData = [];
                foreach ($param['img'] as $img) {
                    $imgData[] = [
                        'img' => $img,
                        'time' => $param['time']
                    ];
                }
                unset($param['img']);
            }
            //获取用户配置
            $TreeUserInfoModel = new TreeUserInfoModel();
            $userInfo = $TreeUserInfoModel->where('uid', '=', $this->userData['id'])->find();
            if ($userInfo['send_is_nickname'] ?? 0) {
                $param['is_nickname'] = 1;
            }
            //处理内容（剔除敏感词）
            $UnitModel = new UnitModel();
            $tree_sensitive = $UnitModel->where('id','=',$this->userData['unit_id'])->value('tree_sensitive');
            if ($tree_sensitive == 1){
                $TreeSensitiveFilterService = new TreeSensitiveFilterService($this->app);
                $param['content'] = $TreeSensitiveFilterService->filter($this->userData['unit_id'], $param['content']);
                $TreeSensitiveFilterService->updateLexicon($this->userData['unit_id'], $TreeSensitiveFilterService->wordsData);
            }
            //添加智慧果
            $fruit_id = $TreeFruitModel->insertGetId($param);
            if (!empty($imgData)) {
                foreach ($imgData as &$v) {
                    $v['fruit_id'] = $fruit_id;
                }
                $TreeFruitImgModel = new TreeFruitImgModel();
                $TreeFruitImgModel->insertAll($imgData);
            }
            $TreeFruitModel->commit();
            return success();
        } catch (\Exception $e) {
            $TreeFruitModel->rollback();
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 智慧果删除
     * @return bool|string
     */
    public function del(): bool|string
    {
        try {
            $id = $this->request->param('id');
            $TreeFruitModel = new TreeFruitModel();
            if (is_array($id)) {
                $TreeFruitModel->where('id', 'in', $id)->update([
                    'is_del' => 1,
                    'del_time' => time()
                ]);
            } else {
                $info = $TreeFruitModel->find($id);
                if (!$info) throw new \Exception('参数错误！');
                $info->save([
                    'is_del' => 1,
                    'del_time' => time()
                ]);
            }
            return success();
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 是否开启评论
     * @return bool|string
     */
    public function commentStatus(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param, [
                'id|ID' => 'require|integer',
                'is_comment|评论状态' => 'require|in:0,1',
            ]);
            $TreeFruitModel = new TreeFruitModel();
            $info = $TreeFruitModel->find($param['id']);
            if (!$info) throw new \Exception('参数错误！');
            $info->save([
                'is_comment' => $param['is_comment'],
            ]);
            return success();
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 修改状态
     * @return bool|string
     */
    public function updateStatus(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param, [
                'id|ID' => 'require|integer',
                'status|状态' => 'require|in:0,1',
            ]);
            $TreeFruitModel = new TreeFruitModel();
            $info = $TreeFruitModel->find($param['id']);
            if (!$info) throw new \Exception('参数错误！');
            $info->save([
                'status' => $param['status'],
            ]);
            return success();
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 导入
     * @return bool|string
     */
    public function import(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param, [
                'file' => 'require'
            ]);
            $ext = '.xlsx';
            $save_name = '/upload/' . date('Ym') . '/' . date('d') . '_' . time() . uniqid();
            $file_path = dirname('./public' . $save_name . $ext);
            folder_build($file_path);
            if (!file_put_contents('./public' . $save_name . $ext, file_get_contents($param['file']))) throw new \Exception('文件加载失败！');
            $spreadSheet = IOFactory::load('./public' . $save_name . $ext);
            $sheet = $spreadSheet->getSheet(0);
            $limit = $sheet->getHighestDataRow('A');
            if ($limit < 2) throw new \Exception('请填写导入的内容！');
            $data = $sheet->rangeToArray('A2:A' . $limit, '', true, true);
            $addData = [];
            foreach ($data as $v) {
                if (empty($v)) continue;
                $addData[] = [
                    'unit_id' => $this->userData['unit_id'],
                    'uid' => $this->userData['id'],
                    'type' => 2,
                    'content' => $v[0],
                    'time' => time()
                ];
            }
            $TreeFruitModel = new TreeFruitModel();
            $TreeFruitModel->insertAll($addData);
            return success();
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 下载模板
     * @return false|string
     */
    public function downloadTemplate(): bool|string
    {
        try {
            $type = $this->request->param('type');
            $url = match ($type) {
                "1" => '/template/tree_fruit.xlsx',
                "2" => '/template/tree_sensitive.xlsx',
                default => throw new \Exception('参数错误！'),
            };
            return success($url);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }
}